/**
 * 邮箱设置
 * */
import React, { useState } from 'react';
import { Modal, Input, Form, Select, message, Row, Col } from 'antd';
import { connect } from 'umi';
import { useRequest } from '@/hooks';
import { getEmployeeInfoList } from '@/services/components/userform';
import { saveEmail, checkEmail } from '../../service';

const { Option } = Select;
const formItemLayout = {
    labelCol: {
        sm: { span: 4 }
    },
    wrapperCol: {
        sm: { span: 18 }
    }
};
const emailSuffixDict = ['@vv.cn', '@vv.com.sg', '@gffamilyoffice.com', '@gfam.com.sg', '@wkcfamilyoffice.com.sg'];
const EmailSetting = ({ form, user, handleOnCancel, handleSave, visible }) => {
    const { getFieldDecorator, validateFields, resetFields, getFieldValue } = form;
    const { firstOrgInfo = {} } = user;
    const { firstCompanyCode } = firstOrgInfo;
    const [formValue, setFormValue] = useState(null);
    const employeeRef = React.useRef(null);

    // 搜索人员
    const { data: employeeList, run: fetchEmployeeList, mutate: setEmployeeList } = useRequest(
        tagName =>
            getEmployeeInfoList({
                administrativeOrganizationCode: firstCompanyCode,
                name: tagName
            }),
        {
            debounceInterval: 500,
            manual: true,
            initialData: [],
            formatResult: res => {
                if (res) {
                    const { code, data: resData, msg } = res;
                    if (code === 10000) {
                        if (!employeeRef.current) {
                            employeeRef.current = resData;
                        }
                        return resData;
                    }
                    message.error(msg);
                }
                return undefined;
            }
        }
    );

    const handleEmployeeFocus = () => {
        if (employeeRef.current) {
            setEmployeeList(employeeRef.current);
        }
    };

    const handleSearch = _value => {
        if (_value) {
            fetchEmployeeList(_value.trim());
        }
    };

    React.useEffect(() => {
        if (visible && employeeList?.length === 0) {
            fetchEmployeeList();
        }
    }, [visible]);

    // 保存邮箱
    const { run: handleSaveEmail } = useRequest(() => saveEmail(formValue), {
        manual: true,
        onSuccess: result => {
            const { code, msg } = result;
            if (code === 10000) {
                message.success('操作成功');
                handleSave(true);
                resetFields();
            } else {
                message.error(msg);
            }
        }
    });

    // 检查邮箱是否正确
    const { loading: checkLoading, run: handleCheckEmail } = useRequest(value => checkEmail(value), {
        manual: true,
        onSuccess: result => {
            const { code, msg } = result;
            if (code === 10000) {
                handleSaveEmail();
            } else {
                message.error(msg);
            }
        }
    });

    // 确定
    const handleOk = () => {
        validateFields((err, values) => {
            if (err) {
                return;
            }
            const next = { ...values };
            const { employeeCode, emailSuffix, emailPrefix } = next;
            if (!employeeCode) {
                next.email = emailPrefix + emailSuffix;
            }
            setFormValue(next);
            handleCheckEmail(next);
        });
    };

    // 取消
    const handleCancel = () => {
        resetFields();
        handleOnCancel();
    };

    // // 选择邮箱
    // const handleSelect = (value, option) => {
    //     const { props } = option;
    //     const { email } = props;
    //     form.setFieldsValue({ email });
    //     setTimeout(() => {
    //         form.validateFields(['email'], { force: true });
    //     }, 1000);
    // };
    const getCurrMail = () => {
        const currEmployeeCode = getFieldValue('employeeCode');
        return employeeList?.find(item => item.employeeCode === currEmployeeCode)?.email || '';
    };
    React.useEffect(() => {
        if (getFieldValue('employeeCode')) form.setFieldsValue({ email: getCurrMail() });
    }, [getFieldValue('employeeCode')]);

    const renderEmail = React.useCallback(() => {
        const currEmployeeCode = getFieldValue('employeeCode');
        const flag = Boolean(currEmployeeCode);
        if (flag) {
            return (
                <Form.Item label="接收简历邮箱">
                    {getFieldDecorator('email', {
                        rules: [
                            {
                                required: true,
                                message: '该姓名下无匹配邮箱，请重选姓名或可不选姓名自行输入邮箱',
                                trim: true
                            }
                        ]
                    })(<Input disabled />)}
                </Form.Item>
            );
        }
        return (
            <Form.Item label="接收简历邮箱" style={{ marginBottom: 0 }} required>
                <Row gutter={8}>
                    <Col span={12}>
                        <Form.Item>
                            {getFieldDecorator('emailPrefix', {
                                rules: [{ required: true, message: '请输入接收简历邮箱' }]
                            })(<Input maxLength={20} />)}
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item>
                            {getFieldDecorator('emailSuffix', {
                                initialValue: '@vv.cn'
                            })(
                                <Select style={{ width: '100%' }}>
                                    {emailSuffixDict.map(item => (
                                        <Option value={item} key={item}>
                                            {item}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Form.Item>
                    </Col>
                </Row>
            </Form.Item>
        );
    }, []);
    return (
        <Modal
            title="新增邮箱"
            visible={visible}
            onOk={handleOk}
            onCancel={handleCancel}
            width={640}
            confirmLoading={checkLoading}
        >
            <Form {...formItemLayout} labelAlign="right" style={{ paddingTop: '30px' }}>
                <Form.Item label="姓名">
                    {getFieldDecorator('employeeCode')(
                        <Select
                            showSearch
                            style={{ width: '100%' }}
                            allowClear
                            placeholder="请选择姓名"
                            getPopupContainer={triggerNode => triggerNode.parentElement}
                            onFocus={handleEmployeeFocus}
                            onSearch={handleSearch}
                            filterOption={false}
                        >
                            {employeeList?.map(item => (
                                <Option value={item.employeeCode} key={item.employeeCode} email={item.email}>
                                    {item.employeeName}
                                </Option>
                            ))}
                        </Select>
                    )}
                </Form.Item>
                {renderEmail()}
                <Form.Item label="密码">
                    {form.getFieldDecorator('emailPwd', {
                        rules: [{ required: true, message: '请输入邮箱密码' }]
                    })(
                        <Input.Password
                            placeholder="请输入邮箱密码"
                            type="search"
                            autocomplete="new-password"
                            maxLength={20}
                        />
                    )}
                </Form.Item>
            </Form>
        </Modal>
    );
};
export default connect(({ user }) => ({ user: user.currentUser }))(Form.create()(EmailSetting));
